package example.controller;

import example.model.AuthInfo;
import example.model.MyUserDetail;
import example.service.MyUserDetailService;
import example.utils.Jwts_JWTUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * TODO
 *
 * @author zgq
 * @date 2020/10/22 15:07
 */
@RestController
@RequestMapping("/zn")
public class ZN_LoginController {
    @Autowired
    private Jwts_JWTUtil jwtUtil;

    @Autowired
    private MyUserDetailService userDetailsService;

//    @Autowired
//    @Qualifier("myUserDetailService")
//    private UserDetailsService userDetailsService;

    @PostMapping("/login")
    public AuthInfo login(String username) {
        MyUserDetail userDetails = (MyUserDetail) userDetailsService.loadUserByUsername(username);
        String token = jwtUtil.generateToken(userDetails);
        Claims claims = jwtUtil.parseToken(token);
        return new AuthInfo(token, userDetails);
    }

    @GetMapping("/getCurrent")
    public String getCurrent() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication auth = context.getAuthentication();
        Object principal1 = auth.getPrincipal();


        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        MyUserDetail principal = (MyUserDetail) authentication.getPrincipal();
        System.out.println(principal);
        return principal.getUsername();
    }

    @GetMapping("/test")
    public String test() {
        System.out.println("ddfdsfsadds");
        return "ddfdsfsadds";
    }
}
